package com.xya.direct.recv;


import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * 路由队列-消息消费者
 */
public class Recv02 {
    //定义队列名称
    private final static String EXCHANGE_NAME = "exchange_direct";

    public static void main(String[] args) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setUsername("xya");
        factory.setVirtualHost("/xya");
        factory.setPassword("xya871219");
        factory.setPort(5672);

        //连接工厂创建连接
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();
        //交换机声明
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        String infoRoutingKey = "info";
        String errorRoutingKey = "error";
        String warningrRoutingKey = "warning";

        //获取队列名称
        String queueName = channel.queueDeclare().getQueue();
        //绑定队列和交换机
        channel.queueBind(queueName, EXCHANGE_NAME, infoRoutingKey);
        channel.queueBind(queueName, EXCHANGE_NAME, errorRoutingKey);
        channel.queueBind(queueName, EXCHANGE_NAME, warningrRoutingKey);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
        };
        //监听队列消费信息
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    }
}
